package contact.controller;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.List;

import model.db.User;

import model.db.VerticalResult;

import org.hibernate.HibernateException;
import org.hibernate.Session;

import contact.util.HibernateUtil;

public class VerticalResultsManager {

public User add(User user) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(user);
		session.getTransaction().commit();
		return user;
	}
	

	/**
	 * Get all vertical results given a query id
	 * 
	 * @param id
	 * @return
	 */
	public List<VerticalResult> getVerticalResults(long query_id, int rank) {
		
		
		System.out.println("Inside getVerticalResults");
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<VerticalResult> v=null;
		try {
			
			v = (List<VerticalResult>) session.createQuery("from VerticalResult where query_id=" + query_id + " and rank<=" + rank).list() ;
			
			
			
			
		} catch (HibernateException e) {
			
		//	System.out.println("Insider getvertical reults error ");
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
	//	System.out.println("print size of vertical results for query " +  v.size());
		return v;
	}
	
	
	
	public  ArrayList<ArrayList<VerticalResult>> toList(Hashtable<Long, ArrayList<VerticalResult>> h){
		
		ArrayList<ArrayList<VerticalResult>> l = new ArrayList<ArrayList<VerticalResult>>();
		
		
		Enumeration<Long> enumeration = h.keys();
		while(enumeration.hasMoreElements()){
			
			long id= enumeration.nextElement();
			l.add(h.get(id));
			
		}
		
		ArrayList<ArrayList<VerticalResult>> organized_list = l;
	//	System.out.println("dentro de tolist");
		for(int i =0; i<organized_list.size(); i++){
		 ArrayList<VerticalResult> current = organized_list.get(i);
	 	 for(int j=0; j<current.size(); j++){
				 
				 VerticalResult temp = current.get(j);
				 
				// System.out.println("inside tolist:"+ temp.getId() + "\t"+ temp.getTitle() + "\t"+ temp.getRank());
				 
			 }
		 }
		
		//randomize verticals
		Collections.shuffle(l);
		
		return l;
		
	}
	public Hashtable<Long, ArrayList<VerticalResult>> getVerticalResultsOrganized(
			List<VerticalResult> a) {

		Hashtable<Long, ArrayList<VerticalResult>> h = new Hashtable<Long, ArrayList<VerticalResult>>();

		for (int i = 0; i < a.size(); i++) {

			VerticalResult temp = a.get(i);

			if (h.containsKey(temp.getVertical_id())) {
				ArrayList<VerticalResult> current_lista = h.get(temp
						.getVertical_id());

				current_lista.add(temp);

				h.put(temp.getVertical_id(), current_lista);

			} else {
				ArrayList<VerticalResult> current_lista = new ArrayList<VerticalResult>();
				current_lista.add(temp);
				h.put(temp.getVertical_id(), current_lista);
			}

		}

		
		
		
		return h;

	}
	
	
}
